<?php

namespace app\controller;

use Exception;
use core\Controller;
use core\Validator;

class Signup extends Controller
{
    public function _before()
    {
        echo 'before';
    }

    // 显示注册页面
    public function index(): void
    {
        $this->render('user/signup');
    }

    // 提交注册
    public function check()
    {
        if (!is_post()) {
            abort(403, '只允许 POST 请求');
        }

        // 表单数据
        $data = [
            'username'   => $this->post('username'),
            'password'   => $this->post('password'),
            'csrf_token' => $this->post('csrf_token'),
        ];

        $errors = $this->validateFormData($data);

        dd($errors);

        // $rules  = [
        //     'username' => ['required|between:3,32', '姓名应为 3-32 个字符'],
        //     'password' => ['required|between:6,30', '密码应为 6 个字符及以上'],
        // ];

        // $validate = new Validator($data, $rules, true);

        // if (!$validate->validate()) {
        //     dd($validate->getError());
        //     return $validate->getError();
        // }

        // dump($errors);
    }

    /**
     * 表单数据验证
     *
     * @param array $data
     * @return string|null 错误消息或 null
     */
    private function validateFormData(array $data): ?string
    {
        // 比对验证码
        // $captcha = $this->post('captcha');
        // if (!$captcha || $captcha !== $this->session('captcha')) {
        //     return '验证码错误';
        // }

        $rules  = [
            'username' => [
                'required'     => '用户名不能为空',
                'between:3,32' => '用户名长度必须 3-32 个字符'
            ],
            'password' => [
                'required' => '密码不能为空',
                'min:6'    => '密码至少 6 位',
                'max:30'   => '密码最多 30 位'
            ]
        ];

        $validate = new Validator($data, $rules, false);

        if (!$validate->validate()) {
            return $validate->getError();
        }

        return null;  // 无错误
    }
}
